<script setup lang="ts">
import type {
  DelayRenderProps,
  RegisterParams,
} from './type'
import { useDefineDelayRender } from './defineDelayRender'
import {
  groupRegisterIdentity,
  groupStatusIdentity,
} from './'
// ------------------use------------------
// #region
defineOptions({
  inheritAttrs: false,
})
const props = withDefaults(
  defineProps<DelayRenderProps>(),
  {
    frame: 1,
  },
)
/** 是否处于渲染组内 */
const isGroup = inject(groupStatusIdentity, false)
const register = inject<
  ((p: RegisterParams) => void) | null
    >(groupRegisterIdentity, null)
const [isRender, setIsRender] = useState(false)

const { updataFrameIndex, registerFrameCallback, destroy }
  = useDefineDelayRender(-1)
registerFrameCallback((n: number) => {
  if (props.delay)
    return true
  if (n < props.frame)
    return false
  setIsRender(true)
  return true
})
init()
// #endregion
// ------------------静态变量------------------
// #region

// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region

// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
function init() {
  if (props.delay) {
    delayInit()
    destroy()
  }
  else {
    if (!isGroup) {
      // 启动
      updataFrameIndex()
    }
    else {
      // 注册
      handleRegister()
    }
  }
}
function delayInit() {
  sleep(props.delay).then(() => {
    setIsRender(true)
  })
}
function handleRegister() {
  register?.({
    setStatus: setIsRender,
    frame: props.frame,
  })
  // requestIdleCallback(({ timeRemaining }) => {
  //   console.log(timeRemaining());

  //   if (timeRemaining() > 0) {
  //     register?.({
  //       setStatus: setIsRender,
  //       frame: props.frame
  //     });
  //     console.log('register');
  //   }
  // });
}
// #endregion
</script>

<template>
  <slot v-if="isRender" />
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
